package org.mcjug.model;

import java.util.List;

import org.mcjug.R;
import org.mcjug.YambaApplication;

import winterwell.jtwitter.Twitter.Status;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class UpdateService extends Service {

	private static final String TAG = UpdateService.class.getSimpleName();
	private boolean runFlag = false;
	private Updater updater;
	private YambaApplication yamba;
	public static final String BROADCAST_INTENT_NAME = "org.mcjug.timelinebroadcast";

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();

		yamba = (YambaApplication) getApplication();
		updater = new Updater();

		Log.d(TAG, "onCreate");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		Log.d(TAG, "onStartCommand; runflag is: " + isRunFlag());

		if (!isRunFlag()) {
			Log.d(TAG, "onStartCommand1");
			setRunFlag(true);
			updater.start();
			yamba.setServiceRunning(true);
		}

		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		Log.d(TAG, "onDestroy1");
		if (isRunFlag()) {
			Log.d(TAG, "onDestroy2.1");
			setRunFlag(false);
			updater.interrupt();
			updater = null;
			yamba.setServiceRunning(false);
		}
		super.onDestroy();
		Log.d(TAG, "onDestroy2");
	}

	private class Updater extends Thread {
		List<Status> timeline;

		public Updater() {
			super("UpdateService-Updater");
		}

		@Override
		public void run() {
			UpdateService updateService = UpdateService.this;
			while (updateService.runFlag) {
				Log.d(TAG, "updater looped");
				try {

					int newUpdates = yamba.fetchStatusUpdates();
					if (newUpdates > 0) { // 3
						Log.d(TAG, "We have a new status");
						Intent i = new Intent();
						i.setAction(BROADCAST_INTENT_NAME);
						getApplicationContext()
								.sendBroadcast(
										i,
										updateService
												.getString(R.string.receive_timeline_notifications_permission_name));
					}

					Log.d(TAG,
							"Loop wait time is: "
									+ getResources().getInteger(
											R.integer.service_sleep_time_ms));
					Thread.sleep(getResources().getInteger(
							R.integer.service_sleep_time_ms));
					Log.d(TAG, "Done sleeping");
				} catch (Throwable e) {
					Log.d(TAG, "Error in the update loop, runflag set to false");
					updateService.runFlag = false;
				}
				Log.d(TAG, "Done looping");
			}

		}

	}

	public boolean isRunFlag() {
		return runFlag;
	}

	public void setRunFlag(boolean runFlag) {
		Log.d(TAG, "Runflag about to be set to " + runFlag);
		this.runFlag = runFlag;
	}
}
